/**
 * 项目名：	Rumba Plan
 * 
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2007，所有权利保留。
 * 
 * 文件名：	Table.java
 * 模块说明：	
 * 修改历史：
 * Jun 8, 2007 - zhangyanbo - 创建。
 */
package com.hd123.rumba.report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 表定义
 * <p>
 * 定义数据集的表结构，支持嵌套数据表定义。
 * 
 * @author zhangyanbo
 * 
 */
public class TableDef {

  private String name;
  private List<Field> fields;
  private HashMap<String, Integer> indexes = new HashMap<String, Integer>();
  private HashMap<String, TableDef> tableDefs = new HashMap<String, TableDef>();
  private TableDef parent;

  public TableDef() {
    super();
    fields = new ArrayList<Field>();
    tableDefs = new HashMap<String, TableDef>();
  }

  public Field addField(Field field) throws Exception {
    if (getField(field.getName()) != null)
      throw new Exception("列 " + field.getName() + " 已经存在。");
    int index = fields.size();
    if (field.getFieldType() != Field.NESTED) {
      for (int i = fields.size() - 1; i >= 0; i--) {
        if (fields.get(i).getFieldType() != Field.NESTED) {
          index = i + 1;
          break;
        }
      }
    }
    fields.add(index, field);
    buildIndexes();
    if (field.getFieldType() == Field.NESTED) {
      TableDef table = new TableDef();
      table.setName(field.getName());
      table.parent = this;
      tableDefs.put(field.getName(), table);
    }
    return field;
  }

  public Field addField(String name, int fieldType, boolean required, int width) throws Exception {
    Field f = new Field();
    f.name = name;
    f.fieldType = fieldType;
    f.required = required;
    f.width = width;
    return addField(f);
  }

  public Field addField(String name, int fieldType, boolean required) throws Exception {
    return addField(name, fieldType, required, 0);
  }

  public Field addField(String name, int fieldType) throws Exception {
    return addField(name, fieldType, false);
  }

  private void buildIndexes() throws Exception {
    indexes.clear();
    for (int i = 0; i < fields.size(); i++)
      indexes.put(fields.get(i).getName().toUpperCase(), Integer.valueOf(i));
  }

  public Field getField(String fieldName) {
    for (int i = 0; i < fields.size(); i++)
      if (fields.get(i).getName().equalsIgnoreCase(fieldName))
        return fields.get(i);
    return null;
  }

  public TableDef getTableDef(String fieldName) {
    return tableDefs.get(fieldName);
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public TableDef getParent() {
    return parent;
  }

  public List<Field> getFields() {
    return fields;
  }

  public Integer field2Index(String fieldName) throws Exception {
    Integer index = indexes.get(fieldName.toUpperCase());
    if (index == null)
      throw new Exception("在数据集中未定义列 " + fieldName);
    return index;
  }

}
